#!/bin/bash

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
clear
printf "
#######################################################################
#                   Install/Uninstall letsencrypt                     #
#######################################################################
"

# get pwd
sed -i "s@^oneinstack_dir.*@oneinstack_dir=`pwd`@" ./options.conf

. ./versions.txt
. ./options.conf
. ./include/color.sh
. ./include/memory.sh
. ./include/check_os.sh
. ./include/download.sh
. ./include/get_char.sh

Install_letsencrypt() {
if [ "$CentOS_RHEL_version" == '7' ];then
    [ ! -e /etc/yum.repos.d/epel.repo ] && cat > /etc/yum.repos.d/epel.repo << EOF
[epel]
name=Extra Packages for Enterprise Linux 7 - \$basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/\$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=\$basearch
failovermethod=priority
enabled=1
gpgcheck=0
EOF
elif [ "$CentOS_RHEL_version" == '6' ];then
    [ ! -e /etc/yum.repos.d/epel.repo ] && cat > /etc/yum.repos.d/epel.repo << EOF
[epel]
name=Extra Packages for Enterprise Linux 6 - \$basearch
#baseurl=http://download.fedoraproject.org/pub/epel/6/\$basearch
mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=\$basearch
failovermethod=priority
enabled=1
gpgcheck=0
EOF
fi

cd $oneinstack_dir/src
src_url=https://dl.eff.org/certbot-auto && Download_src
/bin/mv certbot-auto /usr/local/bin/
chmod +x /usr/local/bin/certbot-auto
certbot-auto -n
certbot-auto -h | grep '\-\-standalone' > /dev/null && echo; echo "${CSUCCESS}Let's Encrypt client installed successfully! ${CEND}"
}

Uninstall_letsencrypt() {
rm -rf /usr/local/bin/cerbot-auto /etc/letsencrypt /var/log/letsencrypt
[ "$OS" == 'CentOS' ] && Cron_file=/var/spool/cron/root || Cron_file=/var/spool/cron/crontabs/root
sed -i '/certbot-auto/d' $Cron_file
echo; echo "${CMSG}Let's Encrypt client uninstall completed${CEND}";
}

ACTION_FUN() {
while :; do
    echo
    echo 'Please select an action:'
    echo -e "\t${CMSG}1${CEND}. install"
    echo -e "\t${CMSG}2${CEND}. uninstall"
    read -p "Please input a number:(Default 1 press Enter) " ACTION
    [ -z "$ACTION" ] && ACTION=1
    if [[ ! $ACTION =~ ^[1,2]$ ]];then
        echo "${CWARNING}input error! Please only input number 1,2${CEND}"
    else
        break
    fi
done
}

while :;do
    printf "
What Are You Doing?
\t${CMSG}1${CEND}. Install/Uninstall Let's Encrypt client
\t${CMSG}q${CEND}. Exit
"
    read -p "Please input the correct option: " Number
    if [[ ! $Number =~ ^[1,q]$ ]];then
        echo "${CFAILURE}input error! Please only input 1 or q${CEND}"
    else
        case "$Number" in
        1)
            ACTION_FUN
            if [ $ACTION = 1 ];then
                Install_letsencrypt
            else
                Uninstall_letsencrypt
            fi
            ;;
        q)
            exit
            ;;
        esac
    fi
done
